using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using SecuBat.AttackPlugin;
using SecuBat.Crawling;
using System.Globalization;
using System.Configuration;

namespace SecuBat.UI
{
	/// <summary>
	/// Summary description for ReportForm.
	/// </summary>
	public class ReportForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.ComboBox comboBoxRuns;
		private System.Windows.Forms.Button buttonShowResponse;

		private int _selectedAttackId;
        private DataGridView dataGridWebPages;
        private DataGridView dataGridWebForms;
        private DataGridView dataGridAttacks;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public ReportForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			DataSet runs = CrawlDbManager.GetCrawlerRuns();
            runs.Tables[0].Locale = CultureInfo.CurrentUICulture;
            runs.Tables[0].Columns.Add("DisplayText", typeof(string), "Name + ' (' + BeginTime + ')'");
            comboBoxRuns.DataSource = runs.Tables[0];
            comboBoxRuns.DisplayMember = "DisplayText";
			comboBoxRuns.ValueMember = "ID";

			buttonShowResponse.Enabled = false;

		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.comboBoxRuns = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.buttonShowResponse = new System.Windows.Forms.Button();
            this.dataGridWebPages = new System.Windows.Forms.DataGridView();
            this.dataGridWebForms = new System.Windows.Forms.DataGridView();
            this.dataGridAttacks = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridWebPages)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridWebForms)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridAttacks)).BeginInit();
            this.SuspendLayout();
            // 
            // comboBoxRuns
            // 
            this.comboBoxRuns.DisplayMember = "BeginTime";
            this.comboBoxRuns.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxRuns.Location = new System.Drawing.Point(98, 11);
            this.comboBoxRuns.Name = "comboBoxRuns";
            this.comboBoxRuns.Size = new System.Drawing.Size(352, 21);
            this.comboBoxRuns.TabIndex = 1;
            this.comboBoxRuns.ValueMember = "ID";
            this.comboBoxRuns.SelectedIndexChanged += new System.EventHandler(this.comboBoxRuns_SelectedIndexChanged);
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(13, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(79, 23);
            this.label1.TabIndex = 2;
            this.label1.Text = "Crawling Run:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(16, 48);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 23);
            this.label2.TabIndex = 3;
            this.label2.Text = "Webpages:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(16, 312);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(64, 23);
            this.label3.TabIndex = 5;
            this.label3.Text = "Webforms:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(16, 528);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(64, 23);
            this.label4.TabIndex = 7;
            this.label4.Text = "Attacks:";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // buttonShowResponse
            // 
            this.buttonShowResponse.Location = new System.Drawing.Point(16, 792);
            this.buttonShowResponse.Name = "buttonShowResponse";
            this.buttonShowResponse.Size = new System.Drawing.Size(112, 23);
            this.buttonShowResponse.TabIndex = 8;
            this.buttonShowResponse.Text = "Show Response";
            this.buttonShowResponse.Click += new System.EventHandler(this.buttonShowResponse_Click);
            // 
            // dataGridWebPages
            // 
            this.dataGridWebPages.AllowUserToAddRows = false;
            this.dataGridWebPages.AllowUserToDeleteRows = false;
            this.dataGridWebPages.AllowUserToResizeRows = false;
            this.dataGridWebPages.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridWebPages.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridWebPages.Location = new System.Drawing.Point(16, 74);
            this.dataGridWebPages.MultiSelect = false;
            this.dataGridWebPages.Name = "dataGridWebPages";
            this.dataGridWebPages.ReadOnly = true;
            this.dataGridWebPages.RowHeadersVisible = false;
            this.dataGridWebPages.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dataGridWebPages.Size = new System.Drawing.Size(912, 232);
            this.dataGridWebPages.TabIndex = 14;
            this.dataGridWebPages.SelectionChanged += new System.EventHandler(this.dataGridWebPages_SelectionChanged);
            // 
            // dataGridWebForms
            // 
            this.dataGridWebForms.AllowUserToAddRows = false;
            this.dataGridWebForms.AllowUserToDeleteRows = false;
            this.dataGridWebForms.AllowUserToResizeRows = false;
            this.dataGridWebForms.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridWebForms.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridWebForms.Location = new System.Drawing.Point(16, 338);
            this.dataGridWebForms.MultiSelect = false;
            this.dataGridWebForms.Name = "dataGridWebForms";
            this.dataGridWebForms.ReadOnly = true;
            this.dataGridWebForms.RowHeadersVisible = false;
            this.dataGridWebForms.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dataGridWebForms.Size = new System.Drawing.Size(912, 187);
            this.dataGridWebForms.TabIndex = 15;
            this.dataGridWebForms.SelectionChanged += new System.EventHandler(this.dataGridWebForms_SelectionChanged);
            // 
            // dataGridAttacks
            // 
            this.dataGridAttacks.AllowUserToAddRows = false;
            this.dataGridAttacks.AllowUserToDeleteRows = false;
            this.dataGridAttacks.AllowUserToResizeRows = false;
            this.dataGridAttacks.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridAttacks.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridAttacks.Location = new System.Drawing.Point(16, 554);
            this.dataGridAttacks.MultiSelect = false;
            this.dataGridAttacks.Name = "dataGridAttacks";
            this.dataGridAttacks.ReadOnly = true;
            this.dataGridAttacks.RowHeadersVisible = false;
            this.dataGridAttacks.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dataGridAttacks.Size = new System.Drawing.Size(912, 232);
            this.dataGridAttacks.TabIndex = 16;
            this.dataGridAttacks.SelectionChanged += new System.EventHandler(this.dataGridAttacks_SelectionChanged);
            // 
            // ReportForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(952, 830);
            this.Controls.Add(this.dataGridAttacks);
            this.Controls.Add(this.dataGridWebForms);
            this.Controls.Add(this.dataGridWebPages);
            this.Controls.Add(this.buttonShowResponse);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.comboBoxRuns);
            this.Name = "ReportForm";
            this.Text = "SecuBat Crawling Report";
            ((System.ComponentModel.ISupportInitialize)(this.dataGridWebPages)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridWebForms)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridAttacks)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion

		private void comboBoxRuns_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			int idRun = (int) comboBoxRuns.SelectedValue;
			if (idRun > 0)
			{
				DataSet pages = CrawlDbManager.GetWebPages(idRun);
                //pages.Tables["Table"].PrimaryKey = new DataColumn[] { pages.Tables["Table"].Columns["ID"] };
                dataGridWebPages.DataSource = pages;
				dataGridWebPages.DataMember = "Table";
			}
		}

        private void dataGridWebPages_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridWebPages.SelectedCells.Count > 0)
            {
                int idPage = (int)dataGridWebPages.SelectedCells[0].OwningRow.Cells["ID"].Value;
                if (idPage > 0)
                {
                    DataSet forms = CrawlDbManager.GetWebForms(idPage);
                    dataGridWebForms.DataSource = forms;
                    dataGridWebForms.DataMember = "Table";
                }
            }
        }

        private void dataGridWebForms_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridWebForms.SelectedCells.Count > 0)
            {
                int idForm = (int)dataGridWebForms.SelectedCells[0].OwningRow.Cells["ID"].Value;
                if (idForm > 0)
                {
                    DataSet attacks = AttackDbManager.GetAttacks(idForm);
                    dataGridAttacks.DataSource = attacks;
                    dataGridAttacks.DataMember = "Table";
                }
            }
		
		}

        private void dataGridAttacks_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridAttacks.SelectedCells.Count > 0)
            {
                _selectedAttackId = (int)dataGridAttacks.SelectedCells[0].OwningRow.Cells["ID"].Value;
                buttonShowResponse.Enabled = _selectedAttackId > 0;
            }
		}

		private void buttonShowResponse_Click(object sender, System.EventArgs e)
		{
			DataSet attackSet = AttackDbManager.GetAttack(_selectedAttackId);
			String response = attackSet.Tables[0].Rows[0][5].ToString();
            String tempPath = ConfigurationManager.AppSettings["TempDir"];
            String tempFileName = Path.Combine(tempPath, "secubattemp.html");

            if (!Directory.Exists(tempPath))
                Directory.CreateDirectory(tempPath);

            if (File.Exists(tempFileName))
                File.Delete(tempFileName);

            using (FileStream fs = File.OpenWrite(tempFileName))
			{
				using (StreamWriter sw = new StreamWriter(fs))
				{
					sw.Write(response);
				}
			}

            Process.Start(tempFileName);
		}



	}
}
